import 'dart:convert';
import 'dart:io';
import 'dart:ui';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluwx/fluwx.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:qunaimedical/components/primary_button.dart';
import 'package:qunaimedical/components/round_checkbox.dart';
import 'package:qunaimedical/init/provider.dart';
import 'package:qunaimedical/models/map_response.dart';
import 'package:qunaimedical/models/user.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/bind_phone.dart';
import 'package:qunaimedical/pages/home.dart';
import 'package:qunaimedical/pages/sms_login.dart';
import 'package:qunaimedical/pages/web_page.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/utils/dialog_utils.dart';
import 'package:qunaimedical/utils/log_utils.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/constants.dart';
import 'package:qunaimedical/values/urls.dart';
import 'package:provider/provider.dart';

class LoginPage extends StatefulWidget {
  static const String routeName = '/login';

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  static String _tag = '_LoginPageState';

  TextEditingController _controller = TextEditingController();

  /// 是否选中
  bool _checked = false;
  final TapGestureRecognizer _recognizer1 = TapGestureRecognizer();

  /// 微信是否安装
  bool _isWeChatInstalled = false;

  @override
  void initState() {
    super.initState();
    _recognizer1.onTap = () {
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (c) => WebPage(type: WebType.terms),
        ),
      );
    };
    _initFluwx();
    fluwx.weChatResponseEventHandler.distinct((a, b) => a == b).listen((res) {
      if (res is fluwx.WeChatAuthResponse) {
        Log.d(_tag, "fluwx res: state :${res.state} code:${res.code}");
        if (res.code != null && res.code.isNotEmpty) {
          _getAccessToken(res.code);
        }
      }
    });
  }

  _initFluwx() async {
    _isWeChatInstalled = await isWeChatInstalled;
    Log.d(_tag, 'isWeChatInstalled：$_isWeChatInstalled');
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        elevation: 0,
        title: Text('登录/注册'),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                margin: EdgeInsets.symmetric(horizontal: 40),
                padding: EdgeInsets.only(top: 20),
                height: 450,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        Image.asset(
                          'assets/images/ic_logo_256.png',
                          width: 80,
                          height: 80,
                        ),
                        Container(
                          margin: EdgeInsets.only(top: 20),
                          child: Text(
                            '欢迎使用群爱互联网平台医生端',
                            style: TextStyle(
                                color: Colors.black87,
                                fontSize: 20,
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                        SizedBox(height: 50),
                        TextField(
                          keyboardType: TextInputType.phone,
                          inputFormatters: [
                            FilteringTextInputFormatter.digitsOnly,
                            LengthLimitingTextInputFormatter(11),
                          ],
                          controller: _controller,
                          decoration: InputDecoration(
                            hintText: '请输入手机号',
                            enabledBorder: UnderlineInputBorder(
                              borderSide: BorderSide(color: Colors.grey[300]),
                            ),
                            focusedBorder: UnderlineInputBorder(
                              borderSide: BorderSide(color: Colors.grey[300]),
                            ),
                          ),
                        ),
                        Row(
                          children: [
                            RoundCheckBox(
                              value: _checked,
                              onChanged: (value) {
                                setState(() {
                                  _checked = value;
                                });
                              },
                            ),
                            Expanded(
                              child: Padding(
                                padding:
                                    const EdgeInsets.symmetric(vertical: 8.0),
                                child: RichText(
                                  text: TextSpan(
                                    children: [
                                      TextSpan(
                                        text: '阅读并同意',
                                        style: TextStyle(
                                            fontSize: 14.0,
                                            color: Colors.black),
                                      ),
                                      TextSpan(
                                        text: '《服务条款》',
                                        style: TextStyle(
                                            fontSize: 14.0,
                                            decoration:
                                                TextDecoration.underline,
                                            color: Colors.blue),
                                        recognizer: _recognizer1,
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                        PrimaryButton(
                          '获取短信验证码',
                          onPressed: _getCode,
                          margin: EdgeInsets.only(top: 40),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              SizedBox(
                height: MediaQuery.of(context).size.height -
                    550 -
                    kToolbarHeight -
                    MediaQuery.of(context).padding.bottom -
                    MediaQuery.of(context).padding.top,
              ),
              Offstage(
                offstage: !Platform.isAndroid,
                child: Container(
                  height: 100,
                  child: InkWell(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Image.asset(
                          'assets/images/ic_wechat.png',
                          width: 40,
                          height: 40,
                          color: Theme.of(context).primaryColor,
                        ),
                        Text(
                          '微信登陆',
                          style: TextStyle(fontSize: 12),
                        ),
                      ],
                    ),
                    onTap: () {
                      if (_checked) {
                        // 微信登陆
                        if (_isWeChatInstalled) {
                          sendWeChatAuth(
                              scope: "snsapi_userinfo", state: "qunai_app");
                        } else {
                          ToastUtil.show('请先安装微信', context);
                        }
                      } else {
                        ToastUtil.show('请先阅读并同意《服务条款》', context);
                      }
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _getCode() async {
    CommonUtils.hideKeyboard(context);
    if (_controller.text.trim().length != 11) {
      ToastUtil.show('请输入有效的手机号。', context);
      return;
    }
    if (!_checked) {
      ToastUtil.show('请先阅读并同意《服务条款》', context);
      return;
    }
    DialogUtils.showWaitDialog(context);
    var data = await XHttp.postFormData(
        Urls.GET_VERIFICATION_CODE, {"phoneNumber": _controller.text.trim()});
    Navigator.pop(context);
    if (data != null) {
      Map<String, dynamic> response = data as Map<String, dynamic>;
      if (response['code'] == 1) {
        Navigator.pushNamed(context, SMSLoginPage.routeName,
            arguments: _controller.text.trim());
      } else {
        ToastUtil.show(response['msg'], context);
      }
    }
  }

  void _getAccessToken(String code) async {
    DialogUtils.showWaitDialog(context);
    String url =
        'https://api.weixin.qq.com/sns/oauth2/access_token?appid=${Constants.wechatAppID}&secret=${Constants.wechatAppSecret}&code=$code&grant_type=authorization_code';
    var data = await XHttp.get(url);
    if (data != null) {
      Map<String, dynamic> response = json.decode(data);
      if (response.containsKey('access_token')) {
        String accessToken = response['access_token'];
        String openid = response['openid'];
        String urlUserInfo =
            "https://api.weixin.qq.com/sns/userinfo?access_token=$accessToken&openid=$openid";
        var infoStr = await XHttp.get(urlUserInfo);
        if (infoStr != null) {
          _checkWXAccount(infoStr);
        } else {
          Navigator.pop(context);
        }
      } else {
        Navigator.pop(context);
      }
    } else {
      Navigator.pop(context);
    }
  }

  void _checkWXAccount(String wxInfo) async {
    var wxId = json.decode(wxInfo)['unionid'];
    var data = await XHttp.get('${Urls.CHECK_WXID}?wxId=$wxId');
    if (data != null) {
      var response = MapResponse.fromJson(data);
      if (response.code == 200) {
        if (response.data.isNotEmpty) {
          // 登陆成功
          User user = User.fromJson(response.data);
          context.read<StoreInfo>().updateUser(user);
          // 登录成功，判断是否有IM账号，没有的话直接注册。
          await CommonUtils.loginIM(context, user.username);
          Navigator.popUntil(context, ModalRoute.withName(HomePage.routeName));
        } else {
          Navigator.pop(context);
          // 新用户，需要绑定手机号。
          Navigator.push(context,
              MaterialPageRoute(builder: (c) => BindPhonePage(wxInfo)));
        }
      } else {
        Navigator.pop(context);
        ToastUtil.show(response.msg, context);
      }
    } else {
      Navigator.pop(context);
    }
  }
}
